﻿using System;
using EkStudio.com.bean.xml.reflection;
using EkStudio.com.bean.xml.RootInterface;
using EkStudio.com.bean.xml.RootInterface.DataSource;
using EkStudio.com.bean.xml.RootInterface.FieldEvent;
using EkStudio.com.bean.xml.RootInterface.language;
using EkStudio.com.bean.xml.RootInterface.Plugin;
using EkStudio.com.bean.xml.Unit;
using EkStudio.com.common.unit;
using System.Collections.Generic;
using EkStudio.com.bean.xml.RootInterface.Field;
using EkStudio.com.bean.xml.RootInterface.QuerySource;
using System.Text;
using EkStudio.com.bean.xml.ProjectVersion;

namespace EkStudio.com.bean.xml.BillModule
{
    [XmlRootElement("root")]
    public class BillModuleItem : BillFormatModule
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(BillModuleItem));

        private BillModuleRoot billModule;
        private BillSourceRoot dataSource;
        private BillQuerySourceRoot querySource;
        private BillUiGroupRoot uiField;
        private BillDataFillRoot dataFill;
        private BillExpandCodeRoot expandCode;
        private BillFieldsI18nRoot i18nProperties;

        [XmlElement("gsModuleProperties")]
        public BillModuleRoot BillModule
        {
            get
            {
                return billModule;
            }

            set
            {
                billModule = value;
            }
        }
        [XmlElement("gsDataSource")]
        public BillSourceRoot DataSource
        {
            get
            {
                return dataSource;
            }

            set
            {
                dataSource = value;
            }
        }
        [XmlElement]
        public BillQuerySourceRoot QuerySource
        {
            get
            {
                return querySource;
            }

            set
            {
                querySource = value;
            }
        }
        [XmlElement("fieldsProperties")]
        public BillUiGroupRoot UiField
        {
            get
            {
                return uiField;
            }

            set
            {
                uiField = value;
            }
        }
        [XmlElement("dataFillProperties")]
        public BillDataFillRoot DataFill
        {
            get
            {
                return dataFill;
            }

            set
            {
                dataFill = value;
            }
        }
        [XmlElement("personalityProperties")]
        public BillExpandCodeRoot ExpandCode
        {
            get
            {
                return expandCode;
            }

            set
            {
                expandCode = value;
            }
        }
        [XmlElement("i18nProperties")]
        public BillFieldsI18nRoot I18nProperties
        {
            get
            {
                return i18nProperties;
            }

            set
            {
                i18nProperties = value;
            }
        }
        [XmlTransient]
        public object ParentBean
        {
            get
            {
                return null;
            }

            set
            {

            }
        }

        public object Clone()
        {
            BillModuleItem clone = new BillModuleItem();
            
            if (billModule != null)
            {
                clone.BillModule = ((BillModuleRoot)billModule.Clone());
            }
            if (uiField != null)
            {
                BillUiGroupRoot clUiField = (BillUiGroupRoot)uiField.Clone();
                clone.UiField = clUiField;
            }
            else
            {
                clone.uiField = new BillUiGroupRoot();
                clone.uiField.Maxid = 1;
                clone.uiField.FieldsProperties = new List<BillUiGroupItems>();
            }
            if (DataFill != null)
            {
                clone.DataFill = (BillDataFillRoot)dataFill.Clone();
            }
            if (expandCode != null)
            {
                clone.ExpandCode = (BillExpandCodeRoot)expandCode.Clone();
            }
            return clone;
        }

        public string getKey()
        {
            return this.billModule.Key;
        }

        public string getCaption()
        {
            return this.billModule.Caption;
        }

        public void setReadOnly(bool read)
        {

        }

        public bool isReadOnly()
        {
            return false;
        }

        public string getJavaPackage()
        {
            return this.billModule.JavaPackage;
        }

        public int getBillType()
        {
            return ProjectUtil.TYPE_BILL_MODULE;
        }

        public string getLanguageText()
        {
            return this.billModule.LanguageTexts;
        }

        public string getVersion()
        {
            return this.billModule.RootVersion;
        }

        /// <summary>
        /// 初始化数据源
        /// </summary>
        public void autoInitDataSource()
        {
            //只有在内容在非只读的情况下执行
            BillSourceRoot sourceRoot = null;
            List<BillSourceTabItems> billTabs = null;
            if (this.DataSource != null)
            {         //如果已经存在数据源根节点
                sourceRoot = this.DataSource;
                if (sourceRoot.TableItems != null)
                { //判断是否存在内容
                    billTabs = sourceRoot.TableItems;
                }
                else
                {
                    billTabs = new List<BillSourceTabItems>();
                    sourceRoot.TableItems = billTabs;
                }
            }
            else
            {
                sourceRoot = new BillSourceRoot();
                billTabs = new List<BillSourceTabItems>();
                sourceRoot.TableItems = billTabs;
                this.DataSource = sourceRoot;
            }
            for (int i = 0; i < billTabs.Count; i++)
            {
                if (billTabs[i].Fields != null)
                {
                    billTabs[i].Fields.Clear();
                }
                else
                {
                    billTabs[i].Fields = new List<BillSourceFields>();
                }
            }
            //			logger.info("billTabsCount="+billTabsCount);
            List<BillUiGroupItems> groups = null;
            if (this.uiField != null && this.uiField.FieldsProperties != null)
            {
                groups = this.uiField.FieldsProperties;
            }

            if (groups != null && groups.Count > 0)
            {
                for (int i = 0; i < groups.Count; i++)
                {
                    BillUiGroupItems group = groups[i];
                    List<BillUiFieldsItem> fields = group.Fields;
                    if (!group.Table)
                    {//1、处理主表数据
                        BillSourceTabItems sourceTab = null;
                        if (billTabs.Count > 0) sourceTab = billTabs[0];
                        if (sourceTab == null)
                        {
                            sourceTab = new BillSourceTabItems();
                            sourceTab.Key = "0";
                            sourceTab.CanSave = true;
                            sourceTab.TableName = "Kt_" + this.getKey();
                            sourceTab.Fields = new List<BillSourceFields>();
                            billTabs.Add(sourceTab);
                        }
                        sourceTab.Caption = this.getCaption();
                        if (sourceTab.Fields == null) sourceTab.Fields = new List<BillSourceFields>();
                        if (fields != null && fields.Count > 0)
                        {
                            for (int k = 0; k < fields.Count; k++)
                            {
                                BillUiFieldsItem field = fields[k];
                                string dataSource = field.DataProperty.DataSource;
                                if (dataSource != null && dataSource != ""&&!field.DataProperty.VirtualType)
                                {
                                    BillSourceFields source = new BillSourceFields();
                                    source.Key = dataSource;
                                    source.Type = field.DataProperty.DataType;
                                    source.Caption = field.Caption;
                                    source.Size = field.DataProperty.Size;
                                    source.DtFormat = field.DataProperty.DtFormat;
                                    source.FnNotNull = field.DataProperty.FnNotNull;
                                    source.LanguageTexts = field.LanguageTexts;
                                    sourceTab.Fields.Add(source);
                                }
                            }
                        }

                    }
                    else
                    {  //处理子表
                        int key = 0;
                        BillSourceTabItems sourceTab = null;
                        if (group.Location == 0)
                        {   //数据源不存在的情况下
                            key = sourceRoot.Maxid + 1;
                            sourceRoot.Maxid = key;
                            group.Location = key;
                            sourceTab = new BillSourceTabItems();
                            sourceTab.CanSave = true;
                            sourceTab.Key = Convert.ToString(key);
                            sourceTab.Caption = string.Format("{0}.{1}", this.getCaption(), group.Caption);
                            sourceTab.TableName = group.TableName;
                            sourceTab.Fields = new List<BillSourceFields>();
                            if (fields != null && fields.Count > 0)
                            {
                                for (int k = 0; k < fields.Count; k++)
                                {
                                    BillUiFieldsItem field = fields[k];
                                    string dataSource = field.DataProperty.DataSource;
                                    if (dataSource != null && dataSource != "")
                                    {
                                        BillSourceFields source = new BillSourceFields();
                                        source.Key = dataSource;
                                        source.Type = field.DataProperty.DataType;
                                        source.Caption = field.Caption;
                                        source.Size = field.DataProperty.Size;
                                        source.DtFormat = field.DataProperty.DtFormat;
                                        source.FnNotNull = field.DataProperty.FnNotNull;
                                        source.LanguageTexts = field.LanguageTexts;
                                        sourceTab.Fields.Add(source);
                                    }
                                }
                            }
                            billTabs.Add(sourceTab);
                        }
                        else
                        {   //数据源存在的情况下
                            for (int k = 0; k < billTabs.Count; k++)
                            {
                                if (billTabs[k].Key == Convert.ToString(group.Location))
                                {
                                    sourceTab = billTabs[k];
                                    break;
                                }
                            }
                            if (sourceTab == null)
                            { //如果数据源丢失
                                sourceTab = new BillSourceTabItems();
                                sourceTab.Key = Convert.ToString(group.Location);
                                sourceTab.TableName = group.TableName;
                                sourceTab.Caption = string.Format("{0}.{1}", this.getCaption(), group.Caption);
                                billTabs.Add(sourceTab);
                                if (group.Location > sourceRoot.Maxid)
                                    sourceRoot.Maxid = group.Location;
                            }
                            else
                            {
                                sourceTab.TableName = group.TableName;
                                sourceTab.Caption = string.Format("{0}.{1}", this.getCaption(), group.Caption);
                            }
                            if (sourceTab.Fields == null) sourceTab.Fields = new List<BillSourceFields>();
                            if (fields != null && fields.Count > 0)
                            {
                                for (int k = 0; k < fields.Count; k++)
                                {
                                    BillUiFieldsItem field = fields[k];
                                    string dataSource = field.DataProperty.DataSource;
                                    if (dataSource != null && dataSource != "")
                                    {
                                        BillSourceFields source = new BillSourceFields();
                                        source.Key = dataSource;
                                        source.Type = field.DataProperty.DataType;
                                        source.Caption = field.Caption;
                                        source.Size = field.DataProperty.Size;
                                        source.DtFormat = field.DataProperty.DtFormat;
                                        source.FnNotNull = field.DataProperty.FnNotNull;
                                        source.LanguageTexts = field.LanguageTexts;
                                        sourceTab.Fields.Add(source);
                                    }
                                }
                            }

                        }
                    }
                }
                //删除无效字段组
                List<string> deleteKey = new List<string>();
                for (int i = 0; i < billTabs.Count; i++)
                {
                    string key = billTabs[i].Key;
                    bool isDelete = true;
                    for (int k = 0; k < groups.Count; k++)
                    {
                        BillUiGroupItems group = (BillUiGroupItems)groups[k];
                        if (group.Location == Convert.ToInt32(key))
                        {
                            isDelete = false;
                            break;
                        }
                    }
                    if (isDelete)
                    {
                        deleteKey.Add(key);
                    }
                }
                for (int i = 0; i < deleteKey.Count; i++)
                {
                    string key = deleteKey[i];
                    for (int k = 0; k < billTabs.Count; k++)
                    {
                        if (billTabs[k].Key == key)
                        {
                            billTabs[k].ParentBean = null;
                            billTabs.RemoveAt(k);
                            break;
                        }
                    }
                }


            }

        }

        /// <summary>
        /// 初始化查询方式
        /// </summary>
        public void autoInitQueryCode()
        {
            bool schemeDefault = false;
            BillQuerySourceRoot root = null;
            if (this.querySource == null)
            {
                root = new BillQuerySourceRoot();
                this.querySource = root;
            }
            else
            {
                root = this.querySource;
            }
            List<BillQuerySchemeItem> chemeList = root.Item;
            if (chemeList == null)
            {
                chemeList = new List<BillQuerySchemeItem>();
                root.Item = chemeList;
            }
            List<BillUiGroupItems> groups = null;
            if (this.uiField != null && this.uiField.FieldsProperties != null) groups = this.uiField.FieldsProperties;
            //主表查询界面
            BillQuerySchemeItem chemeItem = null;

            BillQueryPrinterFields printFields = null;
            BillQueryGeneralFields generalFields = null;
            BillQueryAdvancedFields advancedFields = null;
            BillQuerySqlSource sqlSource = null;

            if (chemeList.Count > 0) chemeItem = chemeList[0];
            if (chemeItem == null)
            {
                chemeItem = new BillQuerySchemeItem();
                chemeItem.Key = this.getKey();
                chemeItem.Caption = this.getCaption();
                chemeItem.LanguageTexts = this.getLanguageText();
                chemeItem.Default_ = true;
                chemeList.Add(chemeItem);
            }
            //获取或者新建显示类
            if (chemeItem.PrinterFields != null)
            {
                printFields = chemeItem.PrinterFields;
                if (printFields.Fields == null)
                    printFields.Fields = new List<BillQueryPrinterItem>();
                if (BeanUtil.VERSION != this.getVersion())
                {
                    printFields.Fields.Clear();
                }
            }
            else
            {
                printFields = new BillQueryPrinterFields();
                printFields.Fields = new List<BillQueryPrinterItem>();
                chemeItem.PrinterFields = printFields;
            }
            //获取或者新建一般查询类
            if (chemeItem.GeneralFields != null)
            {
                generalFields = chemeItem.GeneralFields;
                if (generalFields.Fields == null)
                    generalFields.Fields = new List<BillQueryPrinterItem>();
                generalFields.Fields.Clear();
            }
            else
            {
                generalFields = new BillQueryGeneralFields();
                generalFields.Fields = new List<BillQueryPrinterItem>();
                chemeItem.GeneralFields = generalFields;
            }
            //获取或者新建高级查询类
            if (chemeItem.AdvancedFields != null)
            {
                advancedFields = chemeItem.AdvancedFields;
                if (advancedFields.Fields == null)
                    advancedFields.Fields = new List<BillQueryPrinterItem>();
                advancedFields.Fields.Clear();
            }
            else
            {
                advancedFields = new BillQueryAdvancedFields();
                advancedFields.Fields = new List<BillQueryPrinterItem>();
                chemeItem.AdvancedFields = advancedFields;
            }

            //创建查询语句
            if (chemeItem.SqlSource == null)
            {
                //创建主表SQL语句
                StringBuilder sqlTemp = new StringBuilder();
                if (billModule.Behavior.Tags)
                {
                    sqlTemp.Append("select Kt_").Append(this.getKey()).Append(".*,(case when Sys_ModuleHasRead.module_name is null then 1 else 0 end) has_read from Kt_");
                    sqlTemp.Append(getKey()).Append(" left join Sys_ModuleHasRead on (");
                    sqlTemp.Append("Kt_").Append(this.getKey()).Append(".record_id=module_id and module_name='").Append(this.getKey()).Append("' and Sys_ModuleHasRead.user_id=@user_id)");
                    sqlTemp.Append(" where status =1 ");
                }
                else
                {
                    sqlTemp.Append("select Kt_").Append(this.getKey()).Append(".*,0 has_read from Kt_").Append(getKey()).Append(" ");
                    sqlTemp.Append(" where status =1 ");
                }
                sqlSource = new BillQuerySqlSource();
                sqlSource.Content = sqlTemp.ToString();
                chemeItem.SqlSource = sqlSource;
            }
            #region 添加主表

            //移除不存在的或者不显示的字段
            if (printFields.Fields.Count > 0 && groups != null && groups.Count > 0)
            {
                List<BillQueryPrinterItem> willRemove = new List<BillQueryPrinterItem>();
                foreach (BillQueryPrinterItem pIt in printFields.Fields)
                {
                    bool exist = false;
                    foreach (BillUiGroupItems git in groups)
                    {
                        if (!git.Table && git.Fields != null && git.Fields.Count > 0)
                        {
                            foreach (BillUiFieldsItem field in git.Fields)
                            {
                                if (field.EditProperty.Enable && field.ViewBorder.ShInGrid
                                    && field.Caption == pIt.Caption && field.Key== pIt.Key)
                                {
                                    exist = true;
                                    break;
                                }
                            }
                        }
                        if (exist) break;
                    }
                    if (!exist) willRemove.Add(pIt);
                }
                if (willRemove.Count > 0)
                {
                    foreach (BillQueryPrinterItem pIt in willRemove)
                    {
                        //删除显示
                        chemeItem.PrinterFields.Fields.Remove(pIt);
                    }
                }
            }

            if (groups != null && groups.Count > 0)
            {
                for (int i = 0; i < groups.Count; i++)
                {
                    BillUiGroupItems group = (BillUiGroupItems)groups[i];
                    if (!group.Table && group.Enable)//非子表处理
                    {
                        List<BillUiFieldsItem> fields = group.Fields;
                        if (fields != null && fields.Count > 0)
                        {
                            for (int k = 0; k < fields.Count; k++)
                            {
                                BillUiFieldsItem field = fields[k];
                                if (field.DataProperty.DataSource != "" && (field.DataProperty.EditType == BeanUtil.KT_TEXTFIELD_TYPE
                                        || field.DataProperty.EditType == BeanUtil.KT_MEMOFIELD_TYPE
                                        || field.DataProperty.EditType == BeanUtil.KT_COMBOBOX_TYPE
                                        || field.DataProperty.EditType == BeanUtil.KT_COMBOBOXGRID_TYPE
                                        || field.DataProperty.EditType == BeanUtil.KT_COMBOBOXTREE_TYPE
                                        || field.DataProperty.EditType == BeanUtil.KT_DATEFIELD_TYPE))
                                {
                                    if (field.EditProperty.Enable && field.ViewBorder.ShInGrid)
                                    {
                                        bool exists = false;
                                        //判断当前字段是否已经存在
                                        if (printFields.Fields.Count > 0)
                                        {
                                            foreach (BillQueryPrinterItem QIt in printFields.Fields)
                                            {
                                                if (field.Caption == QIt.Caption && QIt.Key == field.Key)
                                                {
                                                    exists = true;
                                                    break;
                                                }
                                            }
                                        }
                                        if (!exists)
                                        {
                                            //添加显示字段
                                            BillQueryPrinterItem print = new BillQueryPrinterItem();
                                            print.Key = field.Key;
                                            print.Caption = field.Caption;
                                            print.LanguageTexts = field.LanguageTexts;
                                            print.MainField = true;
                                            printFields.Fields.Add(print);
                                        }
                                    }

                                    if (field.EditProperty.Enable && field.ViewBorder.ShSearch)
                                    {
                                        BillQueryPrinterItem gener = new BillQueryPrinterItem();
                                        gener.Key = field.Key;
                                        gener.Caption = field.Caption;
                                        gener.LanguageTexts = field.LanguageTexts;

                                        //添加一般查询字段
                                        if (field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STNONE
                                                || field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STGENERAL)
                                        {
                                            generalFields.Fields.Add(gener);
                                            //添加高级查询字段
                                        }
                                        else if (field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STADVANCED)
                                        {
                                            advancedFields.Fields.Add(gener);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            #endregion

            #region 添加子表查询

            if (groups != null && groups.Count > 0)
            {
                for (int i = 0; i < groups.Count; i++)
                {
                    BillUiGroupItems group = (BillUiGroupItems)groups[i];
                    if (group.Table)
                    {
                        BillQuerySchemeItem SubChemeItem = root.getSchemeByKey(group.Key);
                        if (group.ShowQuery && group.Enable)
                        {
                            if (SubChemeItem == null)
                            {
                                SubChemeItem = new BillQuerySchemeItem();
                                SubChemeItem.Key = group.Key;
                                SubChemeItem.Caption = group.Caption;
                                SubChemeItem.LanguageTexts = group.LanguageTexts;
                                chemeList.Add(SubChemeItem);
                            }
                            //判定是否为默认
                            if (group.SchemeDefaut && !schemeDefault)
                            {
                                root.Item[0].Default_ = false;//主界面为false
                                SubChemeItem.Default_ = true;
                                schemeDefault = true;
                            }
                            else
                            {
                                SubChemeItem.Default_ = false;
                            }
                            //获取或者新建显示类
                            if (SubChemeItem.PrinterFields != null)
                            {
                                if (SubChemeItem.PrinterFields.Fields == null)
                                    SubChemeItem.PrinterFields.Fields = new List<BillQueryPrinterItem>();
                                if (BeanUtil.VERSION != this.getVersion())
                                {
                                    SubChemeItem.PrinterFields.Fields.Clear();
                                }
                            }
                            else
                            {
                                SubChemeItem.PrinterFields = new BillQueryPrinterFields();
                                SubChemeItem.PrinterFields.Fields = new List<BillQueryPrinterItem>();
                            }
                            //获取或者新建一般查询类
                            if (SubChemeItem.GeneralFields != null)
                            {
                                if (SubChemeItem.GeneralFields.Fields == null)
                                    SubChemeItem.GeneralFields.Fields = new List<BillQueryPrinterItem>();
                                SubChemeItem.GeneralFields.Fields.Clear();
                            }
                            else
                            {
                                SubChemeItem.GeneralFields = new BillQueryGeneralFields();
                                SubChemeItem.GeneralFields.Fields = new List<BillQueryPrinterItem>();
                            }

                            //获取或者新建高级查询类
                            if (SubChemeItem.AdvancedFields != null)
                            {
                                if (SubChemeItem.AdvancedFields.Fields == null)
                                    SubChemeItem.AdvancedFields.Fields = new List<BillQueryPrinterItem>();
                                SubChemeItem.AdvancedFields.Fields.Clear();
                            }
                            else
                            {
                                SubChemeItem.AdvancedFields = new BillQueryAdvancedFields();
                                SubChemeItem.AdvancedFields.Fields = new List<BillQueryPrinterItem>();
                            }
                            //创建查询语句[只执行一次]
                            if (SubChemeItem.SqlSource == null)
                            {
                                SubChemeItem.SqlSource = new BillQuerySqlSource();
                                SubChemeItem.SqlSource.Content = "";
                            }

                            //移除不存在的字段
                            if (SubChemeItem.PrinterFields.Fields.Count > 0 && groups != null && groups.Count > 0)
                            {
                                List<BillQueryPrinterItem> willRemove = new List<BillQueryPrinterItem>();
                                foreach (BillQueryPrinterItem pIt in SubChemeItem.PrinterFields.Fields)
                                {
                                    bool exist = false;
                                    foreach (BillUiGroupItems git in groups)
                                    {
                                        if (git.Fields != null && git.Fields.Count > 0)
                                        {
                                            if (git.Enable && (git.Table && git.Key == group.Key || !git.Table))
                                            {
                                                foreach (BillUiFieldsItem field in git.Fields)
                                                {
                                                    if (field.EditProperty.Enable && field.ViewBorder.ShInGrid
                                                        && field.Caption == pIt.Caption && field.Key == pIt.Key)
                                                    {
                                                        exist = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        if (exist) break;
                                    }
                                    if (!exist) willRemove.Add(pIt);
                                }
                                if (willRemove.Count > 0)
                                {
                                    foreach (BillQueryPrinterItem pIt in willRemove)
                                    {
                                        //删除显示
                                        SubChemeItem.PrinterFields.Fields.Remove(pIt);
                                    }
                                }
                            }

                            //添加主表的显示字段及查询
                            foreach (BillUiGroupItems gIt in groups)
                            {
                                if (!gIt.Table && gIt.Enable && gIt.Fields != null && gIt.Fields.Count > 0)
                                {
                                    foreach (BillUiFieldsItem field in gIt.Fields)
                                    {
                                        if (field.DataProperty.DataSource != "" && field.DataProperty.EditType == BeanUtil.KT_TEXTFIELD_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_MEMOFIELD_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_COMBOBOX_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_COMBOBOXGRID_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_COMBOBOXTREE_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_DATEFIELD_TYPE)
                                        {
                                            //添加显示字段
                                            if (field.EditProperty.Enable && field.ViewBorder.ShInGrid)
                                            {
                                                bool exists = false;
                                                //判断当前字段是否已经存在
                                                if (SubChemeItem.PrinterFields.Fields.Count > 0)
                                                {
                                                    foreach (BillQueryPrinterItem QIt in SubChemeItem.PrinterFields.Fields)
                                                    {
                                                        if (field.Caption == QIt.Caption && QIt.Key == field.Key)
                                                        {
                                                            exists = true;
                                                            QIt.MainField = true;
                                                            break;
                                                        }
                                                    }
                                                }
                                                if (!exists)
                                                {
                                                    BillQueryPrinterItem print = new BillQueryPrinterItem();
                                                    print.Key = field.Key;
                                                    print.Caption = field.Caption;
                                                    print.LanguageTexts = field.LanguageTexts;
                                                    print.MainField = true;
                                                    SubChemeItem.PrinterFields.Fields.Add(print);
                                                }
                                            }
                                            //添加查询字段
                                            if (field.EditProperty.Enable && field.ViewBorder.ShSearch)
                                            {
                                                BillQueryPrinterItem gener = new BillQueryPrinterItem();
                                                gener.Key = field.Key;
                                                gener.Caption = field.Caption;
                                                gener.LanguageTexts = field.LanguageTexts;
                                                gener.MainField = true;

                                                //添加一般查询字段
                                                if (field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STNONE
                                                        || field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STGENERAL)
                                                {
                                                    SubChemeItem.GeneralFields.Fields.Add(gener);
                                                    //添加高级查询字段
                                                }
                                                else if (field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STADVANCED)
                                                {
                                                    SubChemeItem.AdvancedFields.Fields.Add(gener);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //添加自己显示字段
                            List<BillUiFieldsItem> fields = group.Fields;
                            StringBuilder subField = new StringBuilder();
                            if (fields != null && fields.Count > 0)
                            {
                                
                                for (int k = 0; k < fields.Count; k++)
                                {
                                    BillUiFieldsItem field = fields[k];
                                    if (field.DataProperty.DataSource != "" && field.DataProperty.EditType == BeanUtil.KT_TEXTFIELD_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_MEMOFIELD_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_COMBOBOX_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_COMBOBOXGRID_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_COMBOBOXTREE_TYPE
                                            || field.DataProperty.EditType == BeanUtil.KT_DATEFIELD_TYPE)
                                    {
                                        //添加显示字段
                                        if (field.EditProperty.Enable && field.ViewBorder.ShInGrid)
                                        {
                                            bool exists = false;
                                            //判断当前字段是否已经存在
                                            if (SubChemeItem.PrinterFields.Fields.Count > 0)
                                            {
                                                foreach (BillQueryPrinterItem QIt in SubChemeItem.PrinterFields.Fields)
                                                {
                                                    if (field.Caption == QIt.Caption && QIt.Key == field.Key)
                                                    {
                                                        exists = true;
                                                        QIt.MainField = false;
                                                        break;
                                                    }
                                                }
                                            }
                                            if (!exists)
                                            {
                                                BillQueryPrinterItem print = new BillQueryPrinterItem();
                                                print.Key = field.Key;
                                                print.Caption = field.Caption;
                                                print.LanguageTexts = field.LanguageTexts;
                                                print.MainField = false;
                                                SubChemeItem.PrinterFields.Fields.Add(print);
                                            }
                                            subField.Append(",").Append(field.DataProperty.DataSource);
                                        }
                                        //添加一般查询字段
                                        if (field.EditProperty.Enable && field.ViewBorder.ShSearch)
                                        {
                                            BillQueryPrinterItem gener = new BillQueryPrinterItem();
                                            gener.Key = field.Key;
                                            gener.Caption = field.Caption;
                                            gener.LanguageTexts = field.LanguageTexts;
                                            gener.MainField = false;

                                            if (field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STNONE
                                                            || field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STGENERAL)
                                            {
                                                SubChemeItem.GeneralFields.Fields.Add(gener);
                                            }
                                            else
                                            {
                                                //添加高级查询
                                                if (field.ViewBorder.SearchType == BeanUtil.KT_QUERY_STADVANCED)
                                                {
                                                    SubChemeItem.AdvancedFields.Fields.Add(gener);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //判定是否生成数据源
                            if (SubChemeItem.SqlSource.Auto || SubChemeItem.SqlSource.Content == "")
                            {
                                //生成数据源
                                string mainTab = this.DataSource.TableItems[0].TableName;
                                StringBuilder sqlTemp = new StringBuilder();
                                if (billModule.Behavior.Tags)
                                {
                                    sqlTemp.Append("select ").Append(mainTab).Append(".*").Append(subField).Append(",(case when Sys_ModuleHasRead.module_name is null then 1 else 0 end) has_read ");
                                    sqlTemp.Append("from ").Append(mainTab);
                                    sqlTemp.Append(" left join ").Append(group.TableName).Append(" on(");
                                    sqlTemp.Append(mainTab).Append(".record_id=").Append(group.TableName).Append(".parent_id and ");
                                    sqlTemp.Append(group.TableName).Append(".status=1)");
                                    sqlTemp.Append(" left join Sys_ModuleHasRead on(module_id=").Append(mainTab).Append(".record_id and module_name='");
                                    sqlTemp.Append(this.getKey()).Append("' and Sys_ModuleHasRead.user_id=@user_id)");
                                    sqlTemp.Append(" where ").Append(mainTab).Append(".status=1");
                                }
                                else
                                {
                                    sqlTemp.Append("select ").Append(mainTab).Append(".*").Append(subField).Append(",0 has_read ");
                                    sqlTemp.Append("from ").Append(mainTab);
                                    sqlTemp.Append(" left join ").Append(group.TableName).Append(" on(");
                                    sqlTemp.Append(mainTab).Append(".record_id=").Append(group.TableName).Append(".parent_id and ");
                                    sqlTemp.Append(group.TableName).Append(".status=1)");
                                    sqlTemp.Append(" where ").Append(mainTab).Append(".status=1");
                                }
                                SubChemeItem.SqlSource.Content = sqlTemp.ToString();
                            }
                        }
                        else
                        {
                            if (SubChemeItem != null)
                            {
                                chemeList.Remove(SubChemeItem);
                            }
                        }

                    }
                }
            }
            #endregion

            if (!schemeDefault && root.Item.Count > 0) root.Item[0].Default_ = true;
            //移除不存在的子表
            if (root.Item != null && root.Item.Count > 1)
            {
                List<BillQuerySchemeItem> list = root.Item;
                for (int i = 1; i < list.Count; i++)
                {//主表不判定
                    BillQuerySchemeItem item = list[i];
                    bool isDelete = true;
                    for (int k = 0; k < groups.Count; k++)
                    {
                        BillUiGroupItems group = (BillUiGroupItems)groups[k];
                        if (group.Enable && group.Table)
                        {
                            if (item.Key == group.Key)
                            {
                                isDelete = false;
                                break;
                            }
                        }

                    }
                    if (isDelete)
                    {
                        root.Item.Remove(item);
                    }
                }
            }
        }

        /// <summary>
        /// 初始化多语言
        /// </summary>
        /// <param name="version"></param>
        public void autoInitLanguage(ProjectVersionItem version)
        {
            if (i18nProperties == null)
            {
                i18nProperties = new BillFieldsI18nRoot();
            }
            if (i18nProperties.Group == null)
            {
                i18nProperties.Group = new List<BillFieldsI18nGroup>();
            }
            List<BillFieldsI18nGroup> groups = i18nProperties.Group;
            if (version != null && version.Languages != null && version.Languages.Item != null)
            {
                List<ProjectLanguageElement> languages = version.Languages.Item;
                for (int i = 0; i < languages.Count; i++)
                {
                    string key = languages[i].Name;
                    string default_ = languages[i].Default_;
                    BillFieldsI18nGroup group = null;
                    for (int k = 0; k < groups.Count; k++)
                    {
                        if (groups[k].Key == key)
                        {
                            group = groups[k];
                            break;
                        }
                    }
                    if (group == null)
                    {
                        group = new BillFieldsI18nGroup();
                        group.Key = key;
                        group.Element = new List<BillFieldsI18nElement>();
                        groups.Add(group);
                    }
                    if (group.Element == null) group.Element = new List<BillFieldsI18nElement>();
                    this.createLanElement(group, (default_ == "Y"));

                    this.createDataFillElement(group, (default_ == "Y"));

                    this.createPluginElement(group, default_ == "Y");
                }

            }

        }

        /// <summary>
        /// 字段组多语言
        /// </summary>
        /// <param name="group"></param>
        /// <param name="default_"></param>
        private void createLanElement(BillFieldsI18nGroup group, bool default_)
        {
            //添加字段组及字段多语言
            if (this.uiField != null && this.uiField.FieldsProperties != null)
            {
                List<BillUiGroupItems> fieldGroup = this.uiField.FieldsProperties;
                for (int i = 0; i < fieldGroup.Count; i++)
                {
                    BillUiGroupItems items = fieldGroup[i];
                    //添加字段组多语言
                    if (!existLanguage(group, items.LanguageTexts,(default_?items.Caption:"")))
                    {
                        BillFieldsI18nElement groupEle = new BillFieldsI18nElement();
                        groupEle.Key = items.LanguageTexts;
                        groupEle.Value = default_ ? items.Caption : "";
                        group.Element.Add(groupEle);
                    }
                    //添加字段多语言
                    if (items.Fields != null && items.Fields.Count > 0)
                    {
                        List<BillUiFieldsItem> item = items.Fields;
                        for (int k = 0; k < item.Count; k++)
                        {
                            BillUiFieldsItem field = item[k];
                            if (!existLanguage(group, field.LanguageTexts,default_?field.Caption:""))
                            {
                                BillFieldsI18nElement ele = new BillFieldsI18nElement();
                                ele.Key = field.LanguageTexts;
                                ele.Value = default_ ? field.Caption : "";
                                group.Element.Add(ele);
                            }
                        }
                    }

                }
            }

        }

        /// <summary>
        /// 数据填充
        /// </summary>
        /// <param name="group"></param>
        /// <param name="default_"></param>
        private void createDataFillElement(BillFieldsI18nGroup group, bool default_)
        {
            if (this.dataFill != null && this.dataFill.LinkEvents != null)
            {
                List<BillDataFillItem> fillList = this.dataFill.LinkEvents;
                for (int i = 0; i < fillList.Count; i++)
                {
                    BillDataFillItem item = fillList[i];
                    if (item.LanguageTexts != "" && !existLanguage(group, item.LanguageTexts,default_?item.Caption:""))
                    {
                        BillFieldsI18nElement ele = new BillFieldsI18nElement();
                        ele.Key = item.LanguageTexts;
                        ele.Value = default_ ? item.Caption : "";
                        group.Element.Add(ele);
                    }

                }
            }
        }
        /// <summary>
        /// 扩展代码多语言
        /// </summary>
        /// <param name="group"></param>
        /// <param name="default_"></param>
        private void createPluginElement(BillFieldsI18nGroup group, bool default_)
        {
            if (this.expandCode != null)
            {
                BillExpandCodeRoot root = this.expandCode;
                if (root.JavaPlugin != null && root.JavaPlugin.JavaItem != null)
                {
                    List<BillExpandJavaCodeItem> javaList = root.JavaPlugin.JavaItem;
                    for (int i = 0; i < javaList.Count; i++)
                    {
                        BillExpandJavaCodeItem item = javaList[i];
                        if (item.LanguageTexts != ""&& !existLanguage(group, item.LanguageTexts,default_?item.Caption:""))
                        {
                            BillFieldsI18nElement ele = new BillFieldsI18nElement();
                            ele.Key = item.LanguageTexts;
                            ele.Value = default_ ? item.Caption : "";
                            group.Element.Add(ele);
                        }
                    }
                }
                if (root.Jscript != null && root.Jscript.Item != null)
                {
                    List<BillExpandJsCodeItem> jsList = root.Jscript.Item;
                    for (int i = 0; i < jsList.Count; i++)
                    {
                        BillExpandJsCodeItem item = jsList[i];
                        if (item.LanguageTexts != ""&& !existLanguage(group, item.LanguageTexts,default_?item.Caption:""))
                        {
                            BillFieldsI18nElement ele = new BillFieldsI18nElement();
                            ele.Key = item.LanguageTexts;
                            ele.Value = default_ ? item.Caption : "";
                            group.Element.Add(ele);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 判断多语言是否已经存在
        /// </summary>
        /// <param name="group"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private bool existLanguage(BillFieldsI18nGroup group,string key,string caption)
        {
            bool result = false;
            if (group != null && group.Element != null)
            {
                foreach(BillFieldsI18nElement i18 in group.Element)
                {
                    if(i18.Key == key)
                    {
                        if(caption != "")//存在时，如果是默认语言则修改为当前
                        {
                            i18.Value = caption;
                        }
                        result = true;
                        break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 刷新多语言
        /// </summary>
        public void updateLanguage()
        {
            if (uiField != null && uiField.FieldsProperties != null && uiField.FieldsProperties.Count > 0)
            {
                uiField.updateLanguageText(this);
            }
            if(dataFill !=null && dataFill.LinkEvents !=null && dataFill.LinkEvents.Count > 0)
            {
                dataFill.updateLanguageText(this);
            }
            if (expandCode != null && expandCode.Jscript != null && expandCode.Jscript.Item!=null && expandCode.Jscript.Item.Count > 0)
            {
                expandCode.Jscript.updateLanguageText(this);
            }
            if (expandCode != null && expandCode.JavaPlugin != null && expandCode.JavaPlugin.JavaItem != null && expandCode.JavaPlugin.JavaItem.Count > 0)
            {
                expandCode.JavaPlugin.updateLanguageText(this);
            }

        }

    }
}
